﻿using System.Windows.Input;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls.Primitives;

namespace VivendoByteToolkit.Helpers
{
    public class SelectionCommandHelper
    {
        public static ICommand GetChanged(DependencyObject obj)
        {
            return (ICommand)obj.GetValue(ChangedProperty);
        }

        public static void SetChanged(DependencyObject obj, ICommand value)
        {
            obj.SetValue(ChangedProperty, value);
        }

        public static readonly DependencyProperty ChangedProperty =
            DependencyProperty.RegisterAttached("Changed",
            typeof(ICommand),
            typeof(SelectionCommandHelper),
            new PropertyMetadata(null,
            new PropertyChangedCallback(Setup)));

        private static void Setup(DependencyObject obj,
            DependencyPropertyChangedEventArgs e)
        {
            Selector ctl = obj as Selector;

            if (ctl != null)
            {
                ICommand oldValue = (ICommand)e.OldValue;
                ICommand newValue = (ICommand)e.NewValue;

                if (oldValue == null && newValue != null)
                {
                    ctl.SelectionChanged += ctl_SelectionChanged;
                }
                else if (oldValue != null && newValue == null)
                {
                    ctl.SelectionChanged -= ctl_SelectionChanged;
                }
            }
        }

        static void ctl_SelectionChanged(object sender, Windows.UI.Xaml.Controls.SelectionChangedEventArgs e)
        {
            var element = sender as FrameworkElement;
            var command = GetChanged(element);

            if (command != null)
            {
                if (command.CanExecute(null))
                {
                    command.Execute(null);
                }
            }
        }
    }
}